import { Toast } from 'mint-ui'
import { message } from './message'
/**
 * 本系统中用于表单验证所需要的方法
 */
/** 表单通用验证规则/函数 **/
/* 手机号正则 */
export const telphoneReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/

/* 身份证正则 */
export const idCardReg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
/* 中文英文字符 */
export const strReg = /^[a-zA-Z_\u4e00-\u9fa5]+$/
/* 包含数字，字母，中文，下划线 */
export const address = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
/* 数字类型 */
export const isNumber = /^[0-9]\d*$/
/* 国内电话号码 */
export const fixedTelphone = /\d{3}-\d{8}|\d{4}-\d{7}/
/* 身份证合法性验证 */
export function idCardValid (idNo, index) {
  const idNumber = idNo ? idNo.toString().toUpperCase() : ''
  const provCodes = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82', '91']
  const lastCodeCheck = () => {
    if (idNumber.length === 18) {
      const chars = idNumber.split('')
      // ∑(ai×Wi)(mod 11)
      // 加权因子
      const factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ]
      // 校验位
      const parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ]
      let sum = 0
      let ai = 0
      let wi = 0
      for (let i = 0; i < 17; i++) {
        ai = chars[i]
        wi = factor[i]
        sum += ai * wi
      }
      const last = parity[sum % 11]
      return last.toString() === chars[17]
    }
    return true
  }
  if (!(idCardReg.test(idNumber) && provCodes.includes(idNumber.substr(0, 2)) && lastCodeCheck()) && typeof index === 'number') {
    if (index === 2) {
      message('配偶信息身份证格式错误')
    } else {
      message('基础信息身份证格式错误')
    }
  }
  return idCardReg.test(idNumber) && provCodes.includes(idNumber.substr(0, 2)) && lastCodeCheck()
}
export function idCardValidate (value) {
  return idCardValid(value) ? true : Toast({
    message: '格式不正确',
    position: 'top',
    duration: 1000
  })
}

export function checkPhone (value) {
  if (!telphoneReg.test(value)) {
    return false
  } else {
    return true
  }
}
